package dao;

import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import entity.Item;
import entity.User;
import util.JpaUtil;

public class UserDao {

	EntityManager em = JpaUtil.getEntityManager();
	
	public User selectUserByEmailAndPassword(String username, String password) {

    	Query q = em.createQuery("SELECT u FROM User u WHERE u.username = :username AND u.password = :password");

		q.setParameter("username", username);
		q.setParameter("password", password);
		
		if(q.getResultList().size() != 0){
			return  (User) q.getResultList().get(0);
		}
		else
			return null;
    }
	
	public void createUser(String username, String password){
		User user = new User(username,password);
		em.getTransaction().begin();
		em.persist(user);
		em.flush();
		em.getTransaction().commit();
	}
	
	public User getUser(String username){
		return null;
	}
	
	//userId comes from the user session's info
    public Set<Item> getUserPastOrderList(int userId){
    	Query q = em.createQuery("SELECT u FROM User u WHERE u.userId = :userId");
    	
    	q.setParameter("userId", userId);
		
		if(q.getResultList().size() != 0){			
			User user = (User) q.getResultList().get(0);
			return user.getPastOrderList();
		}
		return null;		
    }
    
    public Set<Item> getUserBackOrderedList(int userId){
    	Query q = em.createQuery("SELECT u FROM User u WHERE u.userId = :userId");
    	
    	q.setParameter("userId", userId);
		
		if(q.getResultList().size() != 0){
			User user = (User) q.getResultList().get(0);
			return user.getBackOrderedList();
		}	
		return null;		
    }
}
